package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;


    public Client() {

        try {

            System.out.println("正在连接服务器");
            socket = new Socket ("176.108.5.243", 8088);
            System.out.println("服务端启动成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start() {
        try {
            //启动用来读取来自服务端发送过来消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();



            //低级流,作用:将写出的字节发送给建立连接的远端计算机
            OutputStream out = socket.getOutputStream();
            //转换流(高级流),作用:1衔接字节与字符流   2将写出的字符转换为字节
            OutputStreamWriter osw
                    = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            //缓冲流(高级流),作用:块写文本数据加速
            BufferedWriter bw = new BufferedWriter(osw);
            //PrintWriter(高级流),作用:1按行写出字符串  2自动行刷新
            PrintWriter pw = new PrintWriter(bw, true);




            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                /*
                    当我们调用br.readLine()读取来自远端计算机发送过来的一行字符串
                    时,远端计算机如果调用了socket.close()正常与我们断开连接,那么
                    readline()方法会返回null
                    如果客户端是异常中断(比如强制杀死进程),这里readLine()方法会
                    抛出异常
                    java.net.SocketException:Connection rest
                 */

                if ("exit".equals(line)) {
                    pw.close();

                    break;
                }
                pw.println(line);



            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();//与服务器断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    /**
     * 该线程任务负责读取来自服务器发送过来的消息
     */
    class ServerHandler implements Runnable{
        public void run() {
            try {
                //通过sorket获取输入流,来读取远端计算机(服务端)发送过来的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr =
                        new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);

                }
            } catch (IOException e) {

            }
        }
    }
}

